package com.daxia.bumall.web.controller;

import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.daxia.bumall.basemodel.CoreUser;
import com.daxia.bumall.common.CartStatus;
import com.daxia.bumall.dto.AddressDTO;
import com.daxia.bumall.dto.BrowseRecordDTO;
import com.daxia.bumall.dto.CartDTO;
import com.daxia.bumall.dto.UserCartDTO;
import com.daxia.bumall.dto.UserDTO;
import com.daxia.bumall.model.Product;
import com.daxia.bumall.model.Specification;
import com.daxia.bumall.model.User;
import com.daxia.bumall.support.Page;
import com.daxia.bumall.util.SpringSecurityUtils;
import com.daxia.bumall.util.ValidationUtils;

@Controller
@RequestMapping("cart")
public class CartController extends BaseController {

	@ResponseBody
    @RequestMapping(value = "/addCart")
    public String addCart(Long productId,Integer quantity,Long specificationId,Map<String, Object> map) {
    	cartService.addToCart(productId, quantity, specificationId);
    	return okJson();
    }

	@ResponseBody
    @RequestMapping(value = "/addGroupCarts")
	public String addGroupCarts(String cartInfo,Map<String, Object> map) {    //商品组合加入购物车
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
		ValidationUtils.assertTrue(currentUser != null, "您还没有登陆，请登录后使用购物车功能!");
		UserDTO user = new UserDTO();
		user.setId(currentUser.getId());
		ValidationUtils.assertTrue(StringUtils.isNotBlank(cartInfo), "商品组合选择不能为空!");
		List<CartDTO> groupCarts = seprateGroupCartFromStr(cartInfo, user);
		cartService.createCarts(groupCarts);
		return okJson();
	}
	
	
	@ResponseBody
    @RequestMapping(value = "/cartCountOfUser")
	public String getCartCountOfUser(Map<String, Object> map) {
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
		if (currentUser == null) {
			JSONObject jObj = new JSONObject();
			jObj.put("success", true);
			jObj.put("count", "0");
			return jObj.toJSONString();
		}
		Long userId = currentUser.getId();
		//Long userId = 1l;
		int cartCount = cartService.getCartCountOfUser(userId);
		JSONObject jObj = new JSONObject();
		jObj.put("success", true);
		jObj.put("count", cartCount);
		return jObj.toJSONString();
	} 
	
	@ResponseBody
	@RequestMapping(value = "/deleteCart")
	public String deleteCart(Long[] ids,Map<String, Object> map) {   //删除购物车信息
		cartService.deleteByIds(ids);
		return okJson();
	}
	
	@RequestMapping(value = "/cartList")
	public String getCartList(Map<String, Object> map) {
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
		Long userId = currentUser.getId();
		//Long userId = 1l;
		UserDTO user = new UserDTO();
		user.setId(userId);
		CartDTO cart = new CartDTO();
		cart.setUser(user);
		List<CartDTO> cartList = cartService.find(cart, null);   //查出所有的购物车信息
		map.put("carts", cartList);
		List<UserCartDTO> userCarts = manageUserCart(cartList);
		map.put("userCarts",userCarts);
		map.put("products", productService.findRandom(8));
		if (CollectionUtils.isNotEmpty(cartList)) {
			map.put("brand", cartList.get(0).getProduct().getBrand());
		}
		//最近浏览
		BrowseRecordDTO recordDTO = new BrowseRecordDTO();
		recordDTO.setUser(user);
		Page recordPage = new Page();
		recordPage.setPageSize(8);
		map.put("latestRecord",productService.findByBrowse(recordDTO, recordPage));
		return "cart/cart_list";
	}
	
	@RequestMapping(value = "/checkout")
	public String checkout(String cartInfo,Map<String, Object> map) {   //购物车结算
		//ValidationUtils.assertTrue(cartInfo != null && !"".equals(cartInfo), "您没有选择对应的购物车商品进行结算!");
		if(cartInfo != null && !"".equals(cartInfo)) {
			List<CartDTO> carts = seprateCartFromStr(cartInfo);
			for(CartDTO aDto:carts) {
				aDto.setStatus(CartStatus.Choose.getValue());   //状态设置为已选定
			}
			cartService.updateCountAndStatusOfCarts(carts);
		}
		CartDTO queryCart = new CartDTO();
		CoreUser currentUser = SpringSecurityUtils.getCurrentUser();
    	ValidationUtils.assertTrue(currentUser != null, "您还没有登陆，请登录后使用购物车功能!");
    	UserDTO user = new UserDTO();
    	user.setId(currentUser.getId());
    	queryCart.setUser(user);
    	queryCart.setStatus(CartStatus.Choose.getValue());
    	List<CartDTO> checkoutCarts = cartService.find(queryCart, null);
    	AddressDTO queryAddress =new AddressDTO();
    	queryAddress.setUser(user);
    	List<AddressDTO> addresses = addressService.find(queryAddress, null);
    	map.put("provinces", provinceService.findAll());    //查出所有省份
    	map.put("carts", checkoutCarts);
    	map.put("addresses",addresses);
		return "cart/cart_checkout";
	}
	
	public List<CartDTO> seprateGroupCartFromStr(String str,UserDTO user) {   //将前台传过来的组合信息进行分隔成对应的组合商品对象,形式如：651-1-1,652-1-1(商品id-类目-数量)
		List<CartDTO> dtos = new Vector<CartDTO>();
		String[] split = str.split(",");
		for(String aSplit:split) {
			if(aSplit != null && !"".equals(aSplit)) {
				String[] info = aSplit.split("-");
				CartDTO adto = new CartDTO();
				Product product = new Product();
				product.setId(Long.parseLong(info[0]));
				adto.setProduct(product);
				Specification spec = new Specification();
				spec.setId(Long.parseLong(info[1]));
				adto.setSpecification(spec);
				adto.setQuantity(Integer.parseInt(info[2]));
				adto.setStatus(CartStatus.New.getValue());
				adto.setUser(user);
				dtos.add(adto);
 			}
		}
		return dtos;
	}
	
	public List<CartDTO> seprateCartFromStr(String str) {  //将购物车结算信息从字符串中分隔开来，形式如：1-3,2-5（id-数量）
		List<CartDTO> dtos = new Vector<CartDTO>();
		String[] split = str.split(",");
		for(String aSplit:split) {
			if(aSplit != null && !"".equals(aSplit)) {
				String[] info = aSplit.split("-");
				CartDTO adto = new CartDTO();
				adto.setId(Long.parseLong(info[0]));
				adto.setQuantity(Integer.parseInt(info[1]));
				dtos.add(adto);
 			}
		}
		return dtos;
	}
	
	public List<UserCartDTO> manageUserCart(List<CartDTO> cartList) {   //将同一厂家的放在一个里面
		List<CartDTO> copyList = new Vector<CartDTO>(cartList);
		List<UserCartDTO> list = new Vector<UserCartDTO>(); 
		if(copyList != null && copyList.size() > 0) {
			while(copyList.size() > 0) {   //遍历list,找出所有商店数据并整理，直到所有子产品都被分出来
				CartDTO firstCart = copyList.get(0);   //得到第一个购物车信息，并拿出对应的厂家信息
				User proUser = firstCart.getProduct().getUser();
				copyList.remove(0);   //去掉第一个
				if(proUser != null) {   //未知用户，没有关联到，直接干掉
					UserCartDTO userCart = new UserCartDTO();
					userCart.setUser(proUser);
					userCart.setCartList(new Vector<CartDTO>());
					userCart.getCartList().add(firstCart);
					userCart.setBrand(firstCart.getProduct().getBrand());
					for(int i = copyList.size() - 1;i >= 0;i -- ) {   //从后往前遍历,删掉同一个商店的购物信息，并加入到商铺购物车中
						CartDTO theCart = copyList.get(i);
						User theUser = theCart.getProduct().getUser();
						if(theUser != null) {
							if(proUser.getId().longValue() == theUser.getId().longValue()) {   //相同就加入
								userCart.getCartList().add(1,theCart);   //每次遍历到的都放到第二位
								copyList.remove(i);   //然后再删除掉
							}
						}
					}
					list.add(userCart);
				}
			}
		}
		return list;
	}
}	